// models/purchaseOrderModel.js
const db = require('../db');

const PurchaseOrder = {
    // 获取全部采购单
    async getAll() {
        const [rows] = await db.execute('SELECT * FROM purchase_order WHERE status != 2 ORDER BY id DESC');
        return rows;
    },

    // 根据 ID 获取采购单
    async getById(id) {
        const [rows] = await db.execute('SELECT * FROM purchase_order WHERE id = ? AND status != 2', [id]);
        return rows[0];
    },

    // 创建采购单
    async create({ name, numbering, purchaser, project, total_cost }) {
        const [result] = await db.execute(
            `INSERT INTO purchase_order (name, numbering, purchaser, project, total_cost) VALUES (?, ?, ?, ?, ?)`,
            [name, numbering, purchaser, project, total_cost]
        );
        return { id: result.insertId };
    },

    // 更新采购单
    async update(id, { name, numbering, purchaser, project, total_cost, status }) {
        const [result] = await db.execute(
            `UPDATE purchase_order 
       SET name=?, numbering=?, purchaser=?, project=?, total_cost=?, status=?, updated_at=NOW() 
       WHERE id=?`,
            [name, numbering, purchaser, project, total_cost, status, id]
        );
        return result.affectedRows > 0;
    },

    // 逻辑删除采购单
    async delete(id) {
        const [result] = await db.execute(
            `UPDATE purchase_order SET status=2, updated_at=NOW() WHERE id=?`,
            [id]
        );
        return result.affectedRows > 0;
    },
};

module.exports = PurchaseOrder;
